package net.vistiyos.activities;

import java.io.IOException;
import java.util.ArrayList;

import net.vistiyos.R;
import net.vistiyos.model.Hit;
import net.vistiyos.search.searchs;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

public class List extends ListActivity implements OnItemClickListener,OnClickListener{

		int itemsPerPage = 10;
		int pagina=1;
		boolean loadingMore = false;
		FilesTubeListAdapter adapter;
		ArrayList<Hit> data;
		
	    @Override
	    public void onCreate(Bundle savedInstanceState) {    	
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.listplaceholder);
	        data=new ArrayList<Hit>();
	        adapter = new FilesTubeListAdapter(this, android.R.layout.simple_list_item_1,data);
			View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
			this.getListView().addFooterView(footerView);
			this.setListAdapter(adapter);
			this.getListView().setOnItemClickListener(this);
			TextView loadButton=(TextView)findViewById(R.id.empty);
			loadButton.setOnClickListener(this);
			Thread thread =  new Thread(null, loadMoreListItems);
	        thread.start();
	    
	    }
	    

	    private Runnable loadMoreListItems = new Runnable() {			
			@Override
			public void run() {
				loadingMore = true;
		    	Bundle query=List.this.getIntent().getExtras();
		    	try { 
		    		List.this.data=searchs.searchByPage("d1110e796fa4729c30765bea50fe918b", query.getString("query"), List.this.pagina);
		    		pagina++;
			        runOnUiThread(returnRes);
				} catch (Exception e) {
					Builder builder = new Builder(List.this);
					builder.setMessage("An error has ocurred while retrieving data");
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		};	
	
	    private Runnable returnRes = new Runnable() {
	        @Override
	        public void run() {
	        	
				if(data != null && data.size() > 0){
	                for(int i=0;i<data.size();i++)
	                	adapter.add(data.get(i));
	            }
	        	setTitle("Elementos listados: " + String.valueOf(adapter.getCount()));
				adapter.notifyDataSetChanged();
				loadingMore = false;
	        }
	    };

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			Intent i = new Intent(this,Details.class);
			i.putExtra("details", this.data.get(position).getDetails().toString());
			startActivity(i);
		}
		
		private void cargarMasElementos(){
			if(!loadingMore){
				Thread thread =  new Thread(null, loadMoreListItems);
				thread.start();
			}
		}

		@Override
		public void onClick(View v) {
			cargarMasElementos();
		}
		
		private class FilesTubeListAdapter extends ArrayAdapter<Hit> implements OnClickListener {
			
			ArrayList<Hit> items;
			
			public FilesTubeListAdapter(Context context, int textViewResourceId, ArrayList<Hit> items) {
		        super(context, textViewResourceId, items);
		        this.items = items;
			}
			
			 @Override
		     public View getView(int position, View convertView, ViewGroup parent) {
		             View v = convertView;
		             if (v == null) {
		                 LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		                 v = vi.inflate(R.layout.row, null);
		             }
		             Hit o = items.get(position);
		             if (o != null) {
		                     TextView name = (TextView) v.findViewById(R.id.nombre);
		                     if (name != null) {
		                          name.setText("Name: "+o.getName());                            
		                     }
		                     Button abrir=(Button)	v.findViewById(R.id.abrir);
		                     abrir.setTag(position+"open");
		                     abrir.setOnClickListener(this);
		                     Button save=(Button)v.findViewById(R.id.guardar);
		                     save.setTag(position+"save");
		                     save.setOnClickListener(this);
		                     Button details=(Button)v.findViewById(R.id.detalles);
		                     details.setTag(position+"deta");
		                     details.setOnClickListener(this);
		             }
		             return v;
		     }

			@Override
			public void onClick(View v) {
				String tag=v.getTag().toString();
				int indice=Integer.parseInt(v.getTag().toString().substring(0,tag.length()-4));
				if(tag.contains("open")){//Abrir
					Intent i=new Intent("android.intent.action.VIEW",Uri.parse(List.this.adapter.getItem(indice).getAddress().toString()));
					startActivity(i);
				}
				else if(tag.contains("save")){//Guardar
					
				}
				else{//Mostrar detalles
					try {
						Intent i = new Intent(List.this,Details.class);
						i.putExtra("details", List.this.adapter.getItem(indice).serializar());
						startActivity(i);
					} catch (IOException e) {
					}
				}
			}

		}
	}